package com.tiantian.quanminxiu.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;
import com.shenglian.utils.utils.CommonUtils;
import com.tencent.rtmp.ITXLivePushListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePushConfig;
import com.tencent.rtmp.TXLivePusher;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tiantian.quanminxiu.dialog.LiveBeautyDialog;
import com.tiantian.quanminxiu.utils.Constants;
import com.tiantian.quanminxiu.R;
import com.tiantian.quanminxiu.adapter.ChatAdapter;
import com.tiantian.quanminxiu.adapter.UserAvatarAdapter;
import com.tiantian.quanminxiu.api.SocketUtils;
import com.tiantian.quanminxiu.event.LiveRoomEvent;
import com.tiantian.quanminxiu.event.SocketGiftEvent;
import com.tiantian.quanminxiu.event.SocketMsgEvent;
import com.tiantian.quanminxiu.event.SocketStateEvent;
import com.tiantian.quanminxiu.model.ChatMessage;
import com.tiantian.quanminxiu.model.GiftModel;
import com.tiantian.quanminxiu.model.RunwayModel;
import com.tiantian.quanminxiu.model.User;
import com.tiantian.quanminxiu.model.UserInfo;
import com.tiantian.quanminxiu.module.AspectFrameLayout;
import com.tiantian.quanminxiu.presenter.PhoneLookPresent;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.ActivityBase;
import com.tiantian.quanminxiu.utils.EventBusUtils;
import com.tiantian.quanminxiu.utils.UserData;
import com.tiantian.quanminxiu.utils.face.KJChatKeyboard;
import com.tiantian.quanminxiu.utils.gift.BigGiftShowManager;
import com.tiantian.quanminxiu.utils.gift.GiftShowManager;
import com.tiantian.quanminxiu.utils.gift.RunwayShowManager;
import com.tiantian.quanminxiu.view.PhoneLiveView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.pedant.SweetAlert.SweetAlertDialog;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by admin on 2016/8/10.
 */
public class Activity_PhoneLive extends ActivityBase implements PhoneLiveView,KJChatKeyboard.SendMessageListener,ITXLivePushListener,LiveBeautyDialog.OnLiveBeautyCallBack
{

    private TXLivePusher mTXLivePusher;
    private TXLivePushConfig mTXPushConfig;
    private TXCloudVideoView tcVideoView;
    private String Live_URL = "";
    private String Push_URL = "";
    private int RoomId;
    private String Title = "";
    private int fan;
    private int Anchor_Level;
    private String sign = "";
    private int mid;
    private String Anchor_NickName = "";
    private boolean Attention;
    private boolean isBeauty= true;

    private View relRootPhoneLook,vBackOut;
    private View vInputMark,relInputRoot,linTotalContribution,linAnchorInfo;
    private TextView txtUserCount,txtAnchorName,txtBeansCount,txtUserList;
    private ImageView imgBottomChat,imgBottomAdminer,imgBottomShare,imgBottomGiftRecord,imgBottomBeauty,imgBottomSwitch,imgAnchorAvatar,imgLiveCover;
    private RecyclerView mRecyclerView,rvUserAvatar;

    private ChatAdapter chatAdapter;
    private UserAvatarAdapter avatarAdapter;
    private LinearLayoutManager layoutManager;
    private List<ChatMessage> chatList;
    private List<User> userList;

    private GiftShowManager giftShowManager;
    private BigGiftShowManager bigGiftShowManager;
    private RunwayShowManager serviceShowManager,roomShowManager,serviceGiftShowManager,UserJoinShowManager;
    private KJChatKeyboard chatKeyboard;

    LiveBeautyDialog beautyDialog		= null;
    LiveBeautyDialog.BeautyParams	beautyParams		= new LiveBeautyDialog.BeautyParams();

    private int VideoQuality = TXLiveConstants.VIDEO_QUALITY_STANDARD_DEFINITION;

    private PhoneLookPresent present;
    private boolean isJoin;
    private boolean canLive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_live);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);   //应用运行时，保持屏幕高亮，不锁屏
        Init(false);
        EventBusUtils.getInstance().register(this);

        present = new PhoneLookPresent();
        present.attachView(this);

        sign = getIntent().getStringExtra("sign");
        mid = getIntent().getIntExtra("mid", -1);
        RoomId = getIntent().getIntExtra("RoomId",4605);

        InitView();

        setSocketUtils();

        UserData.Reload.Activity_PhoneLook = true;
    }

    //region InitView
    @Override
    public void InitView() {

        tcVideoView = (TXCloudVideoView) findViewById(R.id.tcVideoView);
        txtUserCount = (TextView) findViewById(R.id.txtUserCount);
        txtAnchorName = (TextView) findViewById(R.id.txtAnchorName);
        txtBeansCount = (TextView) findViewById(R.id.txtBeansCount);
        txtUserList = (TextView) findViewById(R.id.txtUserList);
        relRootPhoneLook = findViewById(R.id.relRootPhoneLook);
        vBackOut = findViewById(R.id.vBackOut);
        vInputMark = findViewById(R.id.vInputMark);
        relInputRoot = findViewById(R.id.relInputRoot);
        linAnchorInfo = findViewById(R.id.linAnchorInfo);
        linTotalContribution = findViewById(R.id.linTotalContribution);
        imgLiveCover = (ImageView) findViewById(R.id.imgLiveCover);
        imgAnchorAvatar = (ImageView) findViewById(R.id.imgAnchorAvatar);
        imgBottomShare = (ImageView) findViewById(R.id.imgBottomShare);
        imgBottomChat = (ImageView) findViewById(R.id.imgBottomChat);
        imgBottomAdminer = (ImageView) findViewById(R.id.imgBottomAdminer);
        imgBottomGiftRecord = (ImageView) findViewById(R.id.imgBottomGiftRecord);
        imgBottomBeauty = (ImageView) findViewById(R.id.imgBottomBeauty);
        imgBottomSwitch = (ImageView) findViewById(R.id.imgBottomSwitch);
        mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);
        rvUserAvatar = (RecyclerView) findViewById(R.id.rvUserAvatar);
        layoutManager = new LinearLayoutManager(thisContext);
        mRecyclerView.setLayoutManager(layoutManager);

        LinearLayoutManager UserAvatarLinearLayout = new LinearLayoutManager(thisContext);
        UserAvatarLinearLayout.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvUserAvatar.setLayoutManager(UserAvatarLinearLayout);

        AspectFrameLayout cameraPreview_afl = (AspectFrameLayout) findViewById(R.id.cameraPreview_afl);
        cameraPreview_afl.setShowMode(AspectFrameLayout.SHOW_MODE.FULL);
        chatKeyboard = (KJChatKeyboard) findViewById(R.id.chatKeyboard);
        RelativeLayout relServiceMessage = (RelativeLayout) findViewById(R.id.relServiceMessage);
        RelativeLayout relRoomMessage = (RelativeLayout) findViewById(R.id.relRoomMessage);
        RelativeLayout relUserJoinMessage = (RelativeLayout) findViewById(R.id.relUserJoinMessage);
        RelativeLayout relGiftMessage = (RelativeLayout) findViewById(R.id.relGiftMessage);
        LinearLayout linGiftMessage = (LinearLayout) findViewById(R.id.linGiftMessage);
        ImageView ifcImageView = (ImageView) findViewById(R.id.ifcImageView);
        serviceShowManager = new RunwayShowManager(thisActivity,relServiceMessage);
        serviceGiftShowManager = new RunwayShowManager(thisActivity,relGiftMessage);
        roomShowManager = new RunwayShowManager(thisActivity,relRoomMessage);
        UserJoinShowManager = new RunwayShowManager(thisActivity,relUserJoinMessage);
        giftShowManager = new GiftShowManager(thisActivity,linGiftMessage);
        bigGiftShowManager = new BigGiftShowManager(thisActivity,ifcImageView);

        beautyDialog = new LiveBeautyDialog(this);
        beautyDialog.setScreenMode(0);
        beautyDialog.setLiveBeautyCallBack(beautyParams, this);// 美颜回调

        RxView.clicks(vInputMark).map(View->vInputMark).subscribe(OC_Botton);
        RxView.clicks(vBackOut).map(View->vBackOut).subscribe(OC_Botton);
        RxView.clicks(imgBottomChat).map(View->imgBottomChat).subscribe(OC_Botton);
        RxView.clicks(imgBottomShare).map(View->imgBottomShare).subscribe(OC_Botton);
        RxView.clicks(imgBottomAdminer).map(View->imgBottomAdminer).subscribe(OC_Botton);
        RxView.clicks(imgBottomGiftRecord).map(View->imgBottomGiftRecord).subscribe(OC_Botton);
        RxView.clicks(imgBottomBeauty).throttleFirst(1500, TimeUnit.MILLISECONDS).map(View->imgBottomBeauty).subscribe(OC_Botton);
        RxView.clicks(imgBottomSwitch).throttleFirst(1500, TimeUnit.MILLISECONDS).map(View->imgBottomSwitch).subscribe(OC_Botton);
        RxView.clicks(linAnchorInfo).map(View->linAnchorInfo).subscribe(OC_Botton);
        RxView.clicks(linTotalContribution).map(View->linTotalContribution).subscribe(OC_Botton);

        chatKeyboard.setSendMessageListener(this);
    }
    //endregion

    //region PageInit
    @Override
    public void PageInit(){
        if(!UserData.Reload.Activity_PhoneLook){
            return;
        }
        UserData.Reload.Activity_PhoneLook = false;

        APPUtils.StartLive_To(thisActivity, UserData.Base.NickName, UserData.Base.User_ID);
        txtAnchorName.setText(UserData.Base.NickName);
        imgAnchorAvatar.post(new Runnable() {
            @Override
            public void run() {
                APPUtils.displayImage(APPUtils.createUserAvatar(UserData.Base.User_ID), imgAnchorAvatar, thisActivity, imgAnchorAvatar.getHeight() / 2);
            }
        });
        APPUtils.displayImage(APPUtils.createUserCover(RoomId), imgLiveCover);

        chatList = new ArrayList<ChatMessage>();
        userList = new ArrayList<User>();
        mRecyclerView.setAdapter(chatAdapter = new ChatAdapter(thisActivity, chatList));
        rvUserAvatar.setAdapter(avatarAdapter = new UserAvatarAdapter(thisActivity, userList));

        initPlayer();
    };
    //endregion

    //region 初始化播放器 initPlayer
    private void initPlayer(){
        if (mTXLivePusher == null)
        {
            mTXLivePusher = new TXLivePusher(this);
            mTXLivePusher.setPushListener(this);
            mTXPushConfig = new TXLivePushConfig();
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2)
            {
                mTXPushConfig.setFrontCamera(true);
                mTXPushConfig.setHardwareAcceleration(TXLiveConstants.ENCODE_VIDEO_SOFTWARE);
                mTXPushConfig.setVideoFPS(20);
                mTXPushConfig.setMinVideoBitrate(500);// 动态调整的最小码率
                mTXPushConfig.setMaxVideoBitrate(1000);// 动态调整的最大码率
                mTXPushConfig.setVideoBitrate(800);// 刚启动进入的默认码率
                mTXPushConfig.setAutoAdjustBitrate(false);// 是否开启动态调整码率
                mTXPushConfig.setVideoResolution(TXLiveConstants.VIDEO_RESOLUTION_TYPE_360_640);
                mTXPushConfig.setAutoAdjustStrategy(TXLiveConstants.AUTO_ADJUST_BITRATE_RESOLUTION_STRATEGY_2);
            }
            else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
            {
                mTXPushConfig.setHardwareAcceleration(TXLiveConstants.ENCODE_VIDEO_AUTO);
                mTXPushConfig.setFrontCamera(true);
                mTXPushConfig.setVideoFPS(20);
                mTXPushConfig.setMinVideoBitrate(500);// 动态调整的最小码率
                mTXPushConfig.setMaxVideoBitrate(1000);// 动态调整的最大码率
                mTXPushConfig.setVideoBitrate(800);// 刚启动进入的默认码率
                mTXPushConfig.setAutoAdjustBitrate(false);// 是否开启动态调整码率
                mTXPushConfig.setVideoResolution(TXLiveConstants.VIDEO_RESOLUTION_TYPE_360_640);
                mTXPushConfig.setAutoAdjustStrategy(TXLiveConstants.AUTO_ADJUST_BITRATE_RESOLUTION_STRATEGY_2);
            }
            else
            {// definition 视频质量--0标清，1高清
                mTXPushConfig.setHardwareAcceleration(TXLiveConstants.ENCODE_VIDEO_HARDWARE);
                mTXPushConfig.setFrontCamera(true);
                mTXPushConfig.setVideoFPS(20);
                mTXPushConfig.setMinVideoBitrate(500);// 动态调整的最小码率
                mTXPushConfig.setMaxVideoBitrate(1000);// 动态调整的最大码率
                mTXPushConfig.setVideoBitrate(800);// 刚启动进入的默认码率
                mTXPushConfig.setAutoAdjustBitrate(false);// 是否开启动态调整码率
                mTXPushConfig.setVideoResolution(TXLiveConstants.VIDEO_RESOLUTION_TYPE_360_640);
                mTXPushConfig.setAutoAdjustStrategy(TXLiveConstants.AUTO_ADJUST_BITRATE_RESOLUTION_STRATEGY_2);
            }

            mTXPushConfig.setConnectRetryInterval(30);
            mTXPushConfig.setConnectRetryCount(10);

            mTXLivePusher.setConfig(mTXPushConfig);
        }

        mTXLivePusher.setVideoQuality(VideoQuality,true,true);//qos流控，动态分辨率

        mTXLivePusher.setBeautyFilter(beautyParams.mBeautyStyle, beautyParams.mBeautyProgress, beautyParams.mWhiteProgress, beautyParams.mRuddyProgress);// 当前美颜支持0-9，美白支持0-3

        mTXLivePusher.startCameraPreview(tcVideoView);
    }
    //endregion

    //region SrsEncoder SrsMp4Muxer EventHandler UncaughtExceptionHandler监听
    @Override
    public void onPushEvent(int event, Bundle param)
    {
        if (event < 0) {
            CommonUtils.showToask(thisContext,param.getString(TXLiveConstants.EVT_DESCRIPTION));
            if(event == TXLiveConstants.PUSH_ERR_OPEN_CAMERA_FAIL || event == TXLiveConstants.PUSH_ERR_OPEN_MIC_FAIL){
                clearSocketUtils();
                thisActivity.finish();
            }
        }
        if (event == TXLiveConstants.PUSH_ERR_NET_DISCONNECT) {//网络断连,且经三次抢救无效,可以放弃治疗,更多重试请自行重启推流
            sendLiveMessage("LiveEnd");
            clearSocketUtils();
            thisActivity.finish();
        }
        switch (event){
            case TXLiveConstants.PUSH_EVT_CONNECT_SUCC://已经成功连接到腾讯云推流服务器
                break;
            case TXLiveConstants.PUSH_WARNING_NET_BUSY://网络状况不佳：上行带宽太小，上传数据受阻
                Observable.just("")
                        .delay(1000, TimeUnit.MILLISECONDS)
                        .throttleFirst(1000, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.newThread())
                        .subscribe(str -> {
                            CommonUtils.showToask(thisContext,"网络连接不好...");
                        }, throwable -> {
                            CommonUtils.showToask(thisContext, throwable.getMessage());
                        });
                break;
            case TXLiveConstants.PUSH_WARNING_HW_ACCELERATION_FAIL:
                mTXPushConfig.setHardwareAcceleration(TXLiveConstants.ENCODE_VIDEO_SOFTWARE);
                mTXLivePusher.setConfig(mTXPushConfig);
                break;
        }
    }

    @Override
    public void onNetStatus(Bundle bundle)
    {

    }
    //endregion

    //region 底部按钮事件 OC_Botton
    private Action1<View> OC_Botton =v-> {
        switch (v.getId()){
            case R.id.vInputMark:
                boolean MarkVisibility = relInputRoot.getVisibility()== View.VISIBLE;
                relInputRoot.setVisibility(MarkVisibility?View.GONE:View.VISIBLE);
                chatKeyboard.hideKeyboard(thisContext);
                chatKeyboard.setMessageType(KJChatKeyboard.MSG_CHAT);
                break;
            case R.id.imgBottomChat:
                boolean Visibility = relInputRoot.getVisibility()== View.GONE;
                relInputRoot.setVisibility(Visibility ? View.VISIBLE : View.GONE);
                if(Visibility){
                    chatKeyboard.showKeyboard(thisContext);
                }
                break;
            case R.id.imgBottomShare:
                APPUtils.ShareAppUtils(thisActivity, Anchor_NickName, RoomId,Title);
                break;
            case R.id.imgBottomAdminer:
                //弹出管理员列表
                APPUtils.Dialog_UserList_To(thisActivity, "" + RoomId, relRootPhoneLook);
                break;
            case R.id.imgBottomGiftRecord:
                APPUtils.Dialog_GiftRecord_To(thisActivity, "" + RoomId, relRootPhoneLook);
                break;
            case R.id.imgBottomBeauty:
                beautyDialog.show();
                /*if (isBeauty) {
                    mTXLivePusher.setBeautyFilter(TXLiveConstants.BEAUTY_STYLE_SMOOTH, 0, 0, 0);// 当前美颜支持0-9，美白支持0-3
                    imgBottomBeauty.setImageResource(R.drawable.icon_live_beauty);
                }else{
                    mTXLivePusher.setBeautyFilter(TXLiveConstants.BEAUTY_STYLE_SMOOTH, 6, 2, 2);// 当前美颜支持0-9，美白支持0-3
                    imgBottomBeauty.setImageResource(R.drawable.icon_live_beauty_close);
                }
                isBeauty = !isBeauty;*/
                break;
            case R.id.imgBottomSwitch:
                if (mTXLivePusher!=null) {
                    mTXLivePusher.switchCamera();
                }
                break;
            case R.id.linAnchorInfo:
                APPUtils.Dialog_UserInfoCard_To(thisActivity, RoomId,Anchor_NickName,fan,-1,Anchor_Level,Attention);
                break;
            case R.id.linTotalContribution:
                APPUtils.FanRoll_To(thisActivity, RoomId,Anchor_NickName);
                break;
            case R.id.vBackOut:
                closeActivity();
                break;

        }
    };
    //endregion

    //region onResume onPause onDestroy
    @Override
    protected void onResume() {
        super.onResume();
        PageInit();
        tcVideoView.onResume();

        if (mTXLivePusher != null)
        {
            mTXLivePusher.resumePusher();
        }

        if (mTXLivePusher != null)
        {
            mTXLivePusher.resumeBGM();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        tcVideoView.onPause();
        if (mTXLivePusher != null)
        {
            mTXLivePusher.pauseBGM();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        canLive = false;
        if (tcVideoView!=null)
        {
            tcVideoView.onDestroy();
        }
        if (mTXLivePusher != null)
        {
            mTXLivePusher.stopCameraPreview(false);
            mTXLivePusher.setPushListener(null);
            mTXLivePusher.stopPusher();
        }
        EventBusUtils.getInstance().unregister(this);
        present.detachView();
    }
    //endregion

    //region 发送socket消息 sendLiveMessage(String command,Object... args)
    @Override
    public void sendLiveMessage(String command,Object... args) {
        SocketUtils.getInstance().sendMessage(command, args);
    }
    //endregion

    //region socketUtils设置 setSocketUtils
    @Override
    public void setSocketUtils() {
        SocketUtils.getInstance().bindActivity(thisContext);
    }
    //endregion

    //region 清除socketUtils设置 clearSocketUtils
    @Override
    public void clearSocketUtils() {
        SocketUtils.getInstance().distroySocket();
    }
    //endregion

    //region 接受socket状态消息 receiveStateSocket(SocketStateEvent event)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveStateSocket(SocketStateEvent event){
        if(event.getJsonObject()==null&&event.getSocketTyep()>SocketUtils.CONNECTERROR){
            return;
        }
        JSONObject jsonObject = event.getJsonObject();
        switch (event.getSocketTyep()) {
            case SocketUtils.CONNECTERROR:
            case SocketUtils.DISCONNECT:
                //连接socket服务器出错
                isJoin = false;
                Loading_Open();
                Observable.just("")
                        .delay(1000, TimeUnit.MILLISECONDS)
                        .throttleFirst(1000, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.newThread())
                        .subscribe(str -> {
                            sendLiveMessage("Join", RoomId, UserData.Current.mid + "", Constants.APP_TYPE, UserData.Current.sign);
                        }, throwable -> {
                            CommonUtils.showToask(this.getContext(), throwable.getMessage());
                        });
                break;
            case SocketUtils.CONNECT:
                //连接到socket服务器
                break;
            case SocketUtils.LIVELINSENER:
                //region 主播开播直播监听 LIVELINSENER
                if (jsonObject.optString("flag").equals("0")) {
                    canLive = true;
                    JSONObject jsonData = jsonObject.optJSONObject("Data");
                    String Live_PUSH = jsonData.optString("Live_PUSH");
                    if(!Live_PUSH.isEmpty()&&!Live_PUSH.equalsIgnoreCase(Push_URL)){
                        Push_URL = Live_PUSH;
                        play();
                    }else if(Live_PUSH.isEmpty()){
                        CommonUtils.showToask(thisContext, "直播地址不对，请重新登录");
                        finish();
                    }
                }else {
                    canLive = false;
                    CommonUtils.showToask(thisContext, "发送失败:" + jsonObject.optString("message"));
                }
                //endregion
                break;
            case SocketUtils.LIVEBROADCASTLINSENER:
                //region 其他主播开播直播监听 LIVEBROADCASTLINSENER
                String LiveType = jsonObject.optString("Type");
                if("Live".equalsIgnoreCase(LiveType)){
                    canLive = true;
                }else if("LiveEnd-BlockSet".equalsIgnoreCase(LiveType)){
                    canLive = false;
                    mTXLivePusher.stopPusher();
                    anchorNotLive("艺人房间已冻结...");
                }else if(LiveType.contains("LiveEnd")){
                    canLive = false;
                    mTXLivePusher.stopPusher();
                    anchorNotLive("艺人结束直播...");
                }
                //endregion
                break;
            case SocketUtils.GUARDIANLINSENER:
                //region 守护购买通知 LIVEBROADCAST

                //endregion
                break;
            case SocketUtils.GUARDIANBROADCASTLINSENER:
                //region 其他守护监听 LIVEBROADCAST
                JSONObject RoomUserInfo = jsonObject.optJSONObject("RoomUserInfo");
                if (RoomUserInfo!=null) {
                    ChatMessage OtherJosn = new ChatMessage();
                    OtherJosn.setType(1);
                    String User_NickName = RoomUserInfo.optString("NickName");
                    OtherJosn.setUserid(RoomUserInfo.optInt("User_ID"));
                    OtherJosn.setUserlLevel(RoomUserInfo.optInt("Level"));
                    OtherJosn.setUsername(User_NickName);
                    OtherJosn.setWelcomeString(Html.fromHtml("恭喜 " +  "[level"+RoomUserInfo.optInt("Level")+"] "+"<font color='#ffff83'>" + User_NickName + "</font>" + " 成为守护"));
                    AddChatList(OtherJosn);
                }
                //endregion
                break;
            case SocketUtils.BLACKSETBROADCAST:
                //region 踢人监听 BLACKSETBROADCAST
                try{
                    ChatMessage blackMsg = new ChatMessage();
                    blackMsg.setType(1);
                    switch (jsonObject.optInt("Type")){
                        case 1:
                            blackMsg.setWelcomeString(Html.fromHtml("[roomadmin] "+jsonObject.optJSONObject("RoomUserInfo_Admin").optString("NickName")+""+" 设置 "+ jsonObject.optJSONObject("RoomUserInfo").optString("NickName")+ " 禁言"));
                            break;
                        case 2:
                            blackMsg.setWelcomeString(Html.fromHtml("[roomadmin] "+jsonObject.optJSONObject("RoomUserInfo_Admin").optString("NickName")+" 将 "+ jsonObject.optJSONObject("RoomUserInfo").optString("NickName")+ " 踢出房间"));
                            break;
                        case 3:
                            blackMsg.setWelcomeString(Html.fromHtml("[roomadmin] "+jsonObject.optJSONObject("RoomUserInfo_Admin").optString("NickName")+" 解除 "+ jsonObject.optJSONObject("RoomUserInfo").optString("NickName")+ " 禁言"));
                            break;
                        case 4:
                            blackMsg.setWelcomeString(Html.fromHtml("[roomadmin] "+jsonObject.optJSONObject("RoomUserInfo_Admin").optString("NickName")+" 设置 "+ jsonObject.optJSONObject("RoomUserInfo").optString("NickName")+ " 恢复进房"));
                            break;
                    }
                    AddChatList(blackMsg);
                }catch (Exception e){
                    CommonUtils.showToask(thisContext,"解析json数据错误:"+e.getMessage());
                    e.printStackTrace();
                }
                //endregion
                break;
            case SocketUtils.WARNINGSETBROADCAST:
                //region 警告事件监听 WARNINGSETBROADCAST
                JSONObject WarningInfo = jsonObject.optJSONObject("WarningInfo");
                ChatMessage warnMsg = new ChatMessage();
                warnMsg.setType(1);
                warnMsg.setWelcomeString(Html.fromHtml("[officialadmin] <font color='#ffff83'>秩序监管</font>："+WarningInfo.optString("Type")+(WarningInfo.optInt("Integral")>0?"，扣 "+WarningInfo.optInt("Integral")+" 分<br>"+"提醒艺人:"+WarningInfo.optString("Remark")+"</br>":"<br>"+"提醒艺人:"+WarningInfo.optString("Remark")+"</br>")));
                AddChatList(warnMsg);
                //endregion
                break;
            case SocketUtils.OUTBROADCASTLINSENER://
                //region 其他人退出房间监听(未完成) OUTBROADCASTLINSENER
                //修改房间人数
                JSONObject outValue = jsonObject.optJSONObject("RoomUserInfo");
                if (outValue!=null) {
                    try{
                        txtUserList.setText((Integer.parseInt(txtUserList.getText().toString())-1)+"");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }                //endregion
                break;
            case SocketUtils.USERLEVElBROADCASTLINSENER:
                //region 用户升级监听 USERLEVElLINSENER
                JSONObject roomUserInfo = jsonObject.optJSONObject("RoomUserInfo");
                if (roomUserInfo!=null) {
                    String level = roomUserInfo.optString("Level_Name");
                    String nickname = roomUserInfo.optString("NickName");
                    ChatMessage useInfoMsg = new ChatMessage();
                    useInfoMsg.setType(1);
                    useInfoMsg.setUserid(roomUserInfo.optInt("User_ID"));
                    useInfoMsg.setUserlLevel(roomUserInfo.optInt("Level"));
                    useInfoMsg.setUsername(nickname);
                    useInfoMsg.setWelcomeString(Html.fromHtml("恭喜 " +"[level"+roomUserInfo.optInt("Level")+"] "+"<font color='#ffff83'>" + nickname + "</font>" +" 升到 "+ level+" !"));
                    AddChatList(useInfoMsg);
                }
                //endregion
                break;
            case SocketUtils.GUARDIANLISTLINSENER:
                //region 守护列表 GUARDIANLISTLINSENER
                UserData.Current.GuardList = jsonObject.optJSONArray("Data");
                //endregion
                break;
            case SocketUtils.JOINBROADCASTLINSENER:
                //region 其他人进房监听 JOINBROADCASTLINSENER
                JSONObject joinValue = jsonObject.optJSONObject("RoomUserInfo");
                if (joinValue!=null) {
                    RunwayModel vo = new RunwayModel(5);
                    String Usernickname = joinValue.optString("NickName");
                    vo.setUserName(Usernickname);
                    vo.setUserlevel(joinValue.optInt("Level"));
                    vo.setRunwayId(joinValue.optString("User_ID"));
                    UserJoinShowManager.addRunWay(vo);
                    UserJoinShowManager.showRunWay();
                    try{
                        txtUserList.setText((Integer.parseInt(txtUserList.getText().toString())+1)+"");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                //endregion
                break;
            case SocketUtils.USERLISTLINSENER:
                //region 用户列表 USERLISTLINSENER
                userList.clear();
                JSONArray arr = jsonObject.optJSONArray("Data");
                for (int i=0;i<arr.length();i++){
                    User u = new User();
                    JSONObject value = arr.optJSONObject(i);
                    u.setCoin(value.optInt("Coin"));
                    u.setIsAdmin(value.optBoolean("IsAdmin"));
                    u.setUser_ID(value.optInt("User_ID"));
                    u.setIsRoomGuardian(value.optBoolean("RoomGuardian"));
                    u.setSex(value.optInt("Sex"));
                    u.setLevel(value.optInt("Level"));
                    u.setNickName(value.optString("NickName"));
                    u.setIsAnchor(value.optBoolean("IsAnchor"));
                    userList.add(u);
                    avatarAdapter.notifyDataSetChanged();
                }
                txtUserList.setText(userList.size()+"");
                //endregion
                break;
            case SocketUtils.JOINLINSENER:
                //region 发送我的进房信息并监听 JOINLINSENER
                if (jsonObject.optString("flag").equals("0")&&!isJoin) {
                    try {
                        isJoin = true;
                        imgLiveCover.setVisibility(View.GONE);
                        jsonObject = new JSONObject(jsonObject.optString("Data"));
                        boolean isAttention = jsonObject.optBoolean("Attention");//是否关注主播
                        if (isAttention == true) {
                            //隐藏关注按钮
                        }
                        UserData.Base.UserPackage = jsonObject.optJSONArray("UserPackage");
                        Attention = jsonObject.optBoolean("Attention");
                        String MountsInfo = jsonObject.optString("MountsInfo");
                        String Gift = jsonObject.optString("Gift");
                        //RoomInfo
                        JSONObject joinRoomInfo = jsonObject.optJSONObject("RoomInfo");
                        int roomid = joinRoomInfo.optInt("RoomID");
                        boolean isLive = joinRoomInfo.optBoolean("Live");

                        JSONObject joinRoomAnchorInfo = jsonObject.optJSONObject("RoomAnchorInfo");
                        String RoomName = joinRoomAnchorInfo.optString("RoomName");
                        String welcomString = joinRoomAnchorInfo.optString("RoomWelcome");
//                            pNum = joinRoomAnchorInfo.optString("Pomelo");//主播柚子数
                        String Anchor_EXP = joinRoomAnchorInfo.optString("EXP");
                        Anchor_Level = joinRoomAnchorInfo.optInt("Level");
                        UserData.Base.Anchor_Level = Anchor_Level;
                        Anchor_NickName = joinRoomAnchorInfo.optString("NickName");
                        fan = joinRoomAnchorInfo.optInt("Fans");
                        txtUserCount.setText(Title);
                        txtBeansCount.setText(joinRoomAnchorInfo.optString("Beans"));

                        //RoomUserInfo
                        JSONObject joinRoomUserInfo = new JSONObject(jsonObject.optString("RoomUserInfo"));
                        String joinnickname = joinRoomUserInfo.optString("NickName");
                        ChatMessage safeMsg = new ChatMessage();
                        safeMsg.setType(1);
                        safeMsg.setWelcomeString(Html.fromHtml("[officialadmin] 全民秀安全提示：聊天中若涉及财产的操作，冒充官方人员，请联系官方客服核实对方身份，谨防受骗！"));
                        AddChatList(safeMsg);
                        if (!TextUtils.isEmpty(welcomString)) {
                            ChatMessage welMsg = new ChatMessage();
                            welMsg.setType(1);
                            welMsg.setWelcomeString(Html.fromHtml("欢迎 " + "<font color='#ffff83'>[全民秀直播]: </font>" + welcomString));
                            AddChatList(welMsg);
                        }
                        if (!TextUtils.isEmpty(joinnickname)) {
                            ChatMessage giftrechargeInfo = new ChatMessage();
                            giftrechargeInfo.setType(1);
                            giftrechargeInfo.setUserid(joinRoomUserInfo.optInt("User_ID"));
                            giftrechargeInfo.setUserlLevel(joinRoomUserInfo.optInt("Level"));
                            giftrechargeInfo.setUsername(joinnickname);
                            giftrechargeInfo.setWelcomeString(Html.fromHtml("欢迎 " + "[anchorlevel"+Anchor_Level+"] " + "<font color='#ffff83'>" + joinnickname + "</font>" + " 入场"));
                            AddChatList(giftrechargeInfo);
                        }
                        sendLiveMessage("UserList");//请求用户列表
                        sendLiveMessage("GuardianList");//请求守护列表
                        sendLiveMessage("Live",Title);     //发送开始直播信息
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if(!jsonObject.optString("flag").equals("0")){
                    SweetDialog_InitNetworkTips(jsonObject.optString("message"))
                            .setConfirmClickListener(sDialog -> {
                                sendLiveMessage("Join", RoomId, UserData.Current.mid + "", Constants.APP_TYPE, UserData.Current.sign);
                            });
                    SweetDialog_Show();
                }
                Loading_Close();
                //endregion
                break;
            case SocketUtils.RUNWAYBROADCASTLINSENER:
                //region 全服跑道监听 RUNWAYBROADCASTLINSENER
                String Type= jsonObject.optString("Type");
                if(!Type.isEmpty()&&Type.equalsIgnoreCase("Gift")){
                    JSONObject value = jsonObject.optJSONObject("Data");
                    GiftModel g = new GiftModel();
                    g.setNum(value.optInt("GiftNum"));
                    g.setSendName(value.optJSONObject("RoomUserInfo").optString("NickName"));
                    g.setAnchorName(value.optJSONObject("RoomAnchorInfo").optString("NickName"));
                    g.setGiftID(value.optJSONObject("GiftInfo").optInt("id"));
                    g.setGiftName(value.optJSONObject("GiftInfo").optString("Name"));
                    RunwayModel vo = new RunwayModel(1);
                    vo.setGiftModel(g);
                    vo.setUserlevel(value.optJSONObject("RoomUserInfo").optInt("Level"));
                    vo.setRunwayId(value.optJSONObject("RoomAnchorInfo").optString("NickName") + "#" + value.optString("CreateDate"));
                    serviceGiftShowManager.addRunWay(vo);
                    serviceGiftShowManager.showRunWay();
                } else if(!Type.isEmpty()&&Type.equalsIgnoreCase("Guardian")){
                    JSONObject value = jsonObject.optJSONObject("Data");
                    RunwayModel vo = new RunwayModel(4);
                    vo.setUserName(value.optJSONObject("RoomUserInfo").optString("NickName"));
                    vo.setUserlevel(value.optJSONObject("RoomUserInfo").optInt("Level"));
                    vo.setAnchorlevel(value.optJSONObject("RoomAnchorInfo").optInt("Level"));
                    vo.setAnchorName(value.optJSONObject("RoomAnchorInfo").optString("NickName"));
                    vo.setRunwayId(value.optJSONObject("RoomAnchorInfo").optString("NickName") + "#" + value.optString("CreateDate"));
                    serviceGiftShowManager.addRunWay(vo);
                    serviceGiftShowManager.showRunWay();
                }
                //endregion
                break;
            case SocketUtils.HORNBROADCASTLINSENER:
                //region 喇叭监听(其他) HORNBROADCASTLINSENER
                JSONObject HornInfo = jsonObject.optJSONObject("HornInfo");
                Log.i("dd","--HORNBROADCASTLINSENER:"+jsonObject.toString());
                RunwayModel model;
                if (HornInfo.optString("Mode").equalsIgnoreCase("ROOM")){
                    model = new RunwayModel(2);
                    roomShowManager.addRunWay(model);
                }else {
                    model = new RunwayModel(3);
                    serviceShowManager.addRunWay(model);
                }
                model.setContent(jsonObject.optString("HornMessage"));
                model.setUserName(jsonObject.optJSONObject("RoomUserInfo").optString("NickName"));
                model.setAnchorName(jsonObject.optJSONObject("RoomAnchorInfo").optString("NickName"));
                model.setAnchorId(jsonObject.optJSONObject("RoomAnchorInfo").optInt("RoomID"));
                model.setUserId(jsonObject.optJSONObject("RoomUserInfo").optInt("User_ID"));
                if (HornInfo.optString("Mode").equalsIgnoreCase("ROOM")){
                    roomShowManager.showRunWay();
                }else {
                    serviceShowManager.showRunWay();
                }
                //endregion
                break;
            case SocketUtils.HORNLINSENER:
                //region 喇叭监听(我的) HORNLINSENER
                Log.i("dd","--HORNLINSENER:"+jsonObject.toString());
                if (jsonObject.optString("flag").equals("0")) {
                    jsonObject = jsonObject.optJSONObject("Data");
                    JSONObject HornValue = jsonObject.optJSONObject("HornInfo");
                    if (HornValue.optString("Mode").equalsIgnoreCase("ROOM")){
                        model = new RunwayModel(2);
                        roomShowManager.addRunWay(model);
                        model.setContent(jsonObject.optString("HornMessage"));
                        model.setUserName(jsonObject.optJSONObject("RoomUserInfo").optString("NickName"));
                        model.setAnchorName(jsonObject.optJSONObject("RoomAnchorInfo").optString("NickName"));
                        model.setAnchorId(jsonObject.optJSONObject("RoomAnchorInfo").optInt("RoomID"));
                        model.setUserId(jsonObject.optJSONObject("RoomUserInfo").optInt("User_ID"));
                        roomShowManager.showRunWay();
                    }
                } else if(jsonObject.optString("flag").equals("-2")){
                    CommonUtils.showToask(thisContext, jsonObject.optString("message"));
                    APPUtils.Recharge_TO(thisActivity);
                } else {
                    CommonUtils.showToask(thisContext,"发送失败:"+jsonObject.optString("message"));
                }
                break;
            //endregion
        }
    }
    //endregion

    //region 接受socket礼物消息 receiveGiftSocket(SocketGiftEvent event)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveGiftSocket(SocketGiftEvent event){
        if(event.getJsonObject() == null) {
            return;
        }
        Log.i("receiveMessage", "--receiveMessage:" + event.getJsonObject().toString());
        JSONObject jsonObject = event.getJsonObject();
        switch (event.getSocketTyep()) {
            case SocketUtils.POMELOGETLINSENER:
                //region 我领取星星监听 POMELOGETLINSENER
                //endregion
                break;
            case SocketUtils.POMELOPRESENTLINSENER:
                //region 我送星星 POMELOPRESENTLINSENER
                //endregion
                break;
            case SocketUtils.POMELOPRESENTBROADCASTLINSENER:
                //region 其他人送星星监听 POMELOPRESENTBROADCASTLINSENER
                JSONObject RoomAnchorInfo = jsonObject.optJSONObject("RoomAnchorInfo");
                JSONObject jsonUserInfo = jsonObject.optJSONObject("RoomUserInfo");
                String Sendername = jsonUserInfo.optString("NickName");
                ChatMessage pomelopMsg = new ChatMessage();
                pomelopMsg.setType(4);
                pomelopMsg.setUserid(jsonUserInfo.optInt("User_ID"));
                pomelopMsg.setUserlLevel(jsonUserInfo.optInt("Level"));
                pomelopMsg.setUsername(Sendername);
                pomelopMsg.setGiftName("星星");
                pomelopMsg.setGiftCount(jsonObject.optInt("Num"));
                pomelopMsg.setReceiverUserName(Anchor_NickName);
                AddChatList(pomelopMsg);
                //endregion
                break;
            case SocketUtils.GIFTLINSENER:
                //region 我发送礼物监听 GIFTLINSENER
                Log.i("SocketUtils","GIFTLINSENER:"+jsonObject.toString());
                //endregion
                break;
            case SocketUtils.GIFTBROADCASTLINSENER:
                //region 其他人送礼物监听 GIFTBROADCASTLINSENER
                Log.i("dd","--gg:"+jsonObject.toString());
                UserData.Current.addAnchorGift(jsonObject);
                int Num = jsonObject.optInt("GiftNum");
                JSONObject GiftInfo = jsonObject.optJSONObject("GiftInfo");
                int Gift_ID = GiftInfo.optInt("id");

                JSONObject giftRoomUserInfo = jsonObject.optJSONObject("RoomUserInfo");
                JSONObject giftRoomAnchorInfo = jsonObject.optJSONObject("RoomAnchorInfo");

                String sendername = giftRoomUserInfo.optString("NickName");
                String receivername = giftRoomAnchorInfo.optString("NickName");
                GiftModel gift = new GiftModel();
                gift.setShowId(giftRoomUserInfo.optString("User_ID") + "_" + Gift_ID + "_" + Num);
                gift.setUser_ID(giftRoomUserInfo.optInt("User_ID"));
                gift.setGiftName(GiftInfo.optString("Name"));
                gift.setPrice(GiftInfo.optInt("Price"));
                gift.setCount(jsonObject.optInt("GiftCount"));
                gift.setNum(Num);
                gift.setGiftType(jsonObject.optInt("GiftStreamer")==0?0:1);
                gift.setGiftImg(APPUtils.createGiftImg(Gift_ID));
                gift.setSendName(sendername);
                gift.setAnchorName(receivername);
                if (giftShowManager != null) {
                    giftShowManager.addGift(gift);
                    giftShowManager.showGift();
                }

                if (bigGiftShowManager!=null&&judgeBigGiftName(gift.getGiftName()))
                {
                    bigGiftShowManager.addGiftWay(gift);
                }

                ChatMessage giftpMsg = new ChatMessage();
                giftpMsg.setType(4);
                giftpMsg.setUserid(giftRoomUserInfo.optInt("User_ID"));
                giftpMsg.setUserlLevel(giftRoomUserInfo.optInt("Level"));
                giftpMsg.setUsername(giftRoomUserInfo.optString("NickName"));
                giftpMsg.setGiftName(GiftInfo.optString("Name"));
                giftpMsg.setGiftCount(Num);
                giftpMsg.setGiftId(Gift_ID);
                giftpMsg.setReceiverUserName(Anchor_NickName);
                AddChatList(giftpMsg);
                //endregion
                break;
            case SocketUtils.PONDBROADCASTLINSENER:
                //region 直播间奖池监听(未完成) GIFTBROADCASTLINSENER

                //endregion
                break;

        }
    }
    //endregion

    //region 接受socket聊天消息 receiveMsgSocket(SocketMsgEvent event)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveMsgSocket(SocketMsgEvent event) {
        if(event.getJsonObject()==null){
            return;
        }
        Log.i("receiveMessage", "--receiveMessage:" + event.getJsonObject().toString());
        JSONObject jsonObject = event.getJsonObject();
        String Type= jsonObject.optString("Type");
        switch (event.getSocketTyep()) {
            case SocketUtils.MESSAGELINSENER:
                //region 我发送信息监听 MESSAGELINSENER
                if (jsonObject.optString("flag").equals("0")) {
                    jsonObject = jsonObject.optJSONObject("Data");

                    boolean isprivate = jsonObject.optBoolean("Private");
                    String messageString = jsonObject.optString("Message");
                    JSONObject senderjson = jsonObject.optJSONObject("RoomUserInfo");

                    // String receiverjson = jsonObject.optString("Receiver");
                    String senderName = senderjson.optString("NickName");
                    if (jsonObject.optJSONObject("RoomUserInfo_Receiver")!=null) {
                        // 私聊
                        JSONObject RoomUserInfo_Receiver = jsonObject.optJSONObject("RoomUserInfo_Receiver");
                        String receiver = RoomUserInfo_Receiver.optString("NickName");
                        ChatMessage SendInfo = new ChatMessage();
                        SendInfo.setUserlLevel(senderjson.optInt("Level"));
                        SendInfo.setType(3);
                        if(isprivate){
                            SendInfo.setMsgContent(Html.fromHtml("对 " + "<font color='#f5a623'>" +  receiver + "</font>" + " 悄悄说：" + messageString));
                        }else {
                            SendInfo.setMsgContent(Html.fromHtml("对 " + "<font color='#f5a623'>" +  receiver + "</font>" + " 说：" + messageString));
                        }
                        SendInfo.setUsername(senderName);
                        AddChatList(SendInfo);
                    }else {
                        ChatMessage MesValue = new ChatMessage();
                        MesValue.setType(3);
                        MesValue.setUserlLevel(senderjson.optInt("Level"));
                        MesValue.setMsgContent(Html.fromHtml(messageString));
                        MesValue.setUsername(senderName);
                        AddChatList(MesValue);
                    }

                }else {
                    CommonUtils.showToask(thisContext,"发送失败:"+jsonObject.optString("message"));
                }
                //endregion
                break;
            case SocketUtils.MESSAGEBROADCASTLINSENER:
                //region 其他人发送信息监听 MESSAGEBROADCASTLINSENER
                boolean isprivate = jsonObject.optBoolean("Private");
                String messageString = jsonObject.optString("Message");
                JSONObject senderjson = jsonObject.optJSONObject("RoomUserInfo");
                JSONObject RoomUserInfo_Receiver = jsonObject.optJSONObject("RoomUserInfo_Receiver");
                // String receiverjson = jsonObject.optString("Receiver");
                String senderName = senderjson.optString("NickName");
                if (jsonObject.optJSONObject("RoomUserInfo_Receiver")!=null) {
                    // 私聊
                    String receiver = RoomUserInfo_Receiver.optString("NickName");
                    ChatMessage SendInfo = new ChatMessage();
                    SendInfo.setType(3);
                    SendInfo.setUserlLevel(senderjson.optInt("Level"));
                    if(isprivate){
                        SendInfo.setMsgContent(Html.fromHtml("对 " + "<font color='#f5a623'>" +  receiver + "</font>" + " 悄悄说：" + messageString));
                    }else {
                        SendInfo.setMsgContent(Html.fromHtml("对 " + "<font color='#f5a623'>" +  receiver + "</font>" + " 说：" + messageString));
                    }
                    SendInfo.setUsername(senderName);
                    AddChatList(SendInfo);
                } else {
                    // 公共聊天
                    if (!TextUtils.isEmpty(senderName)) {
                        ChatMessage SendInfo = new ChatMessage();
                        SendInfo.setType(3);
                        SendInfo.setUserlLevel(senderjson.optInt("Level"));
                        SendInfo.setMsgContent(Html.fromHtml(messageString));
                        SendInfo.setUsername(senderName);
                        AddChatList(SendInfo);
                    }
                }
                //endregion
                break;
        }
    }
    //endregion

    //region 接受socket聊天消息 receiveMsgSocket(SocketMsgEvent event)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveLiveMsg(LiveRoomEvent event) {
        if(event.getType()==null){
            return;
        }
        switch (event.getType()){
            case "toldHim":
                setMessageType(KJChatKeyboard.MSG_TOLDHIM,event.getReceiveID(),event.getReceiveName());
                break;
            case "privateChat":
                setMessageType(KJChatKeyboard.MSG_PRIVATE, event.getReceiveID(), event.getReceiveName());
                break;
            case "load":
                Title = event.getContent();
                if (event.getReceiveID()>0)//用receiveId接收视频质量
                {
                    VideoQuality = event.getReceiveID();
                    mTXLivePusher.setVideoQuality(VideoQuality,true,true);//qos流控，动态分辨率
                }
                Loading_Open(true);
                break;
            case "finish":
                Observable.just("")
                        .delay(100, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.newThread())
                        .subscribe(str -> {
                            sendLiveMessage("LiveEnd");
                            clearSocketUtils();
                            thisActivity.finish();
                        }, throwable -> {
                            CommonUtils.showToask(this.getContext(), throwable.getMessage());
                        });

                break;
        }
    }
    //endregion

    //region 添加聊天信息 AddChatList
    @Override
    public void AddChatList(ChatMessage msg){
        chatAdapter.addMessage(msg);
        chatAdapter.notifyDataSetChanged();
        F_scrollToLast();
    }
    //endregion

    //region 跳转到ListView底部 F_scrollToLast（）
    private void F_scrollToLast() {
        layoutManager.scrollToPositionWithOffset(chatAdapter.getItemCount() - 1, 0);
    }
    //endregion

    //region 开始播放 play
    @Override
    public void play(){
        if (!TextUtils.isEmpty(Push_URL) && !Push_URL.equals("null")&&canLive) {
            mTXLivePusher.startPusher(Push_URL);
        }
    }
    //endregion

    //region 用户关注 setAttention
    @Override
    public void setAttention() {
    }
    //endregion

    //region 退出直播间 closeActivity
    @Override
    public void closeActivity() {
        SweetDialog_Init(SweetAlertDialog.WARNING_TYPE)
                .setTitleText("提示？")
                .setContentText("您确定要退出直播吗?")
                .setConfirmText("确定")
                .setCancelText("取消")
                .setConfirmClickListener(sDialog -> {
                    sendLiveMessage("LiveEnd");
                    clearSocketUtils();
                    thisActivity.finish();
                });
        SweetDialog_Show();
    }
    //endregion

    @Override
    public void setMessageType(int type, int User_ID, String UserName) {
        chatKeyboard.setMessageType(type,User_ID,UserName);
        relInputRoot.setVisibility(View.VISIBLE);
    }

    //region 艺人不在直播 anchorNotLive
    public void anchorNotLive(){

    }

    public void anchorNotLive(String msg){
        Loading_Close();
        imgLiveCover.setVisibility(View.VISIBLE);
    }
    //endregion

    // region 房间冻结 anchorNotLive
    public void roomBoock(){

    }
    //endregion

    //region 按回退键退出 onKeyDown(int keyCode, KeyEvent event)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closeActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    //endregion

    //region 键盘发送聊天消息 sendChatMessage
    @Override
    public void sendChatMessage(String type,String content) {
        sendLiveMessage(type, content);
    }

    @Override
    public void sendChatMessage(String type, int User_ID, String content, boolean pre) {
        sendLiveMessage(type,content,User_ID,pre);
    }

    @Override
    public void sendChatMessage(String type, String horn, String content) {
        sendLiveMessage(type,horn,content);
    }
    //endregion

    public boolean judgeBigGiftName(String name){
        switch (name){
            case "跑车":
            case "飞机":
            case "航母":
            case "别墅":
            case "游艇":
                return true;
        }
        return false;
    }

    @Override
    public void onDialogDismiss(boolean dismiss)
    {

    }

    @Override
    public void onLiveBeauty(LiveBeautyDialog.BeautyParams beautyParams)
    {// 美颜回调-修改信息
        if (mTXLivePusher != null)
            mTXLivePusher.setBeautyFilter(beautyParams.mBeautyStyle, beautyParams.mBeautyProgress, beautyParams.mWhiteProgress, beautyParams.mRuddyProgress);
    }

    @Override
    public void onBeautyFilter(Bitmap filterBitmap)
    {// 美颜回调--修改-滤镜
        if (mTXLivePusher != null)
            mTXLivePusher.setFilter(filterBitmap);
    }
}
